#!/usr/bin/env python2
#coding=utf-8
import errno

from utils import _dmsg
from utils import _dwarn
from utils import _derror

from utils import _exec_remote
from utils import _exec_shell1

from utils import Exp

class Etcd_manage(object):
    def __init__(self):
        pass

    @classmethod
    def get_lich_admin(cls):
        """
        :return: lich admin host
        """
        cmd = u"lich list |grep 'admin'| awk -F':' '{print $(NF-1)}'"
        (host, err) = _exec_shell1(cmd, p=False)
        if err.strip() != '':
             raise Exp(errno.EPERM, "%s:%s" % (host.strip(), err.strip()))
        return host

    @classmethod
    def etcd_is_health(cls):
        """
        :return:
            return 1: etcd cluster health 
            return 0: etcd cluster unhealth
        """
        host = cls.get_lich_admin()
        cmd = u"etcdctl cluster-health"
        (out, err) = _exec_remote(host.strip(), cmd)
        if err.strip() != '':
            raise Exp(errno.EPERM, "%s:%s" % (host.strip(), err.strip()))
        if "unreachable" in out or "unhealth" in out or "error" in out:
            _dwarn("Etcd status is unhealth, please check etcd status")
            return 0
        else:
            return 1
